package com.push.api.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.push.api.db.DbUtil;
import com.push.api.vo.AppConfig;
import com.push.api.vo.Offer;
import com.push.api.vo.ResultWrapper;

public class OfferListAPI extends BaseSerlvet {

    /**
     * 
     */
    private static final long serialVersionUID = -7130504831217648220L;

    private ObjectMapper mapper = new ObjectMapper();
    
    private int count = 0;
    static Logger logger = LoggerFactory.getLogger("ip_track_log"); 
    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response) {
        
        String packagename = request.getParameter("packagename");
        
        if (packagename == null || packagename.equals("")) {
            System.out.println("invalid request");
            return;
        }
        
        String device = request.getParameter("device");
        System.out.println(count++ + " - " + device);
        logger.debug(device + "\t" + getRemortIP(request));
        AppConfig config = DbUtil.getAppconfig(packagename);
        
        if (config == null) {
            DbUtil.insertNewAppConfig(packagename);
            
            config = DbUtil.getAppconfig(packagename);
        }
        
        List<Offer> list = DbUtil.getOffers();
        
        ResultWrapper result = new ResultWrapper();
        
        result.setAd_close(config.getAd_close());
        result.setC_rate(config.getC_rate());
        result.setInterval(config.getInterval());
        result.setRequest_interval(config.getRequest_interval());
        
        result.setList(list);
        
        try {
            mapper.writeValue(response.getWriter(), result);
        } catch (JsonGenerationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public String getRemortIP(HttpServletRequest request) {

        if (request.getHeader("x-forwarded-for") == null) {

            return request.getRemoteAddr();

        }

        return request.getHeader("x-forwarded-for");

    }
}
